# Joao Lencart e Silva: j.lencart@ua.pt
from datetime import datetime, timedelta
import numpy as np
import sys
def isDigit(val):
    """simple float checker"""
    try:
        float(val)
        return True
    except ValueError:
        return False
    except TypeError:
    # See if the object is iterable if not, return False
        try:
            iter(val)
    # Check if  all elements are convertable to fload: do a cyclic check
            out = True 
            for v in val:
                 out *= isDigit(v)
            return out
        except: return False

def isList(val):
    """Simple list type checker"""
    if type(val).__name__=='list':
        return True
    else:
        return False

def dNum2DTime(date):
    """converts matlab datenum (1 = 0000/01/01 00:00:00) to datetime object
    and from datetime object to datenum""" 
    try:
    # If date is a float (datenum) then convert to gregorian
        date = date - 366.
    # Add fractioned day
        secs = (date - int(date)) * 24. * 60. * 60.
    # Create date object
        do = datetime.fromordinal(int(date))
    # Add fractioned day
        do = do + timedelta(seconds = secs)
        return do
    except TypeError:
    # If date is a datetime object then convert to datenum
        return date.toordinal() + date.hour/24. + date.minute/1440.+\
                date.second/86400. + 366.

def dTime2Loch(date, out = 'float'):
    """Converts pre-industrial baseline date (1760/0/1 00:00:00 UT to datetime
       gregorian ordinal and from datetime object to pre-industrial numeral.
       Optionally returns a datetime object with out = 'do' if the input
       is a numeral.
            Usage:
                dTime2Loch(date, out = 'float') from gregorian to Loch
                dTime2Loch(date, out = 'do') from Loch to gregorian

       """
    try:
    # If date is a float (Loch day) then convert to gregorian
        if out.lower() == 'do':
            date = np.array(date);
            date = date + 642462.
            do = datetime.fromordinal(date)
            dt = timedelta(seconds =  float(date - np.floor(date))*24. *3600.)
            return do + dt
        else:
            return date + 642462.
    except TypeError:
    # If date is a datetime object then convert to pre-industrial baseline
        return date.toordinal() + date.hour/24. + date.minute/1440.+\
                (date.second + date.microsecond * 1.e-6) / 86400. - 642462.
